using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Rendering;

public class SceneStatisticsTool : EditorWindow
{
    private Dictionary<string, int> objectCountByType = new Dictionary<string, int>();
    private Dictionary<string, int> componentCountByType = new Dictionary<string, int>();
    private int totalObjects;
    private int totalComponents;
    private Vector2 scrollPosition;

    [MenuItem("Tools/基础工具/场景统计工具")]
    public static void ShowWindow()
    {
        GetWindow<SceneStatisticsTool>("场景统计");
    }

    void OnGUI()
    {
        GUILayout.Label("场景对象统计", EditorStyles.boldLabel);
        EditorGUILayout.Space();

        if (GUILayout.Button("分析当前场景", GUILayout.Height(30)))
        {
            AnalyzeScene();
        }

        EditorGUILayout.Space();

        if (totalObjects == 0)
        {
            GUILayout.Label("点击\"分析当前场景\"按钮开始统计", EditorStyles.helpBox);
            return;
        }

        scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

        // 总体统计
        GUILayout.Label($"场景统计概览", EditorStyles.boldLabel);
        EditorGUILayout.BeginVertical(GUI.skin.box);
        GUILayout.Label($"总游戏对象: {totalObjects}");
        GUILayout.Label($"总组件数量: {totalComponents}");
        GUILayout.Label($"平均组件数: {(float)totalComponents / totalObjects:F2}");
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        // 对象类型统计
        GUILayout.Label("对象类型分布", EditorStyles.boldLabel);
        EditorGUILayout.BeginVertical(GUI.skin.box);
        foreach (var kvp in objectCountByType.OrderByDescending(x => x.Value))
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label($"{kvp.Key}:", GUILayout.Width(150));
            GUILayout.Label($"{kvp.Value} 个");
            float percentage = (float)kvp.Value / totalObjects * 100;
            GUILayout.Label($"{percentage:F1}%", GUILayout.Width(60));
            EditorGUILayout.EndHorizontal();
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        // 组件类型统计
        GUILayout.Label("组件类型分布", EditorStyles.boldLabel);
        EditorGUILayout.BeginVertical(GUI.skin.box);
        foreach (var kvp in componentCountByType.OrderByDescending(x => x.Value).Take(15)) // 只显示前15个
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label($"{kvp.Key}:", GUILayout.Width(150));
            GUILayout.Label($"{kvp.Value} 个");
            EditorGUILayout.EndHorizontal();
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        // 性能相关统计
        GUILayout.Label("性能相关统计", EditorStyles.boldLabel);
        EditorGUILayout.BeginVertical(GUI.skin.box);

        // 使用新的 FindObjectsByType API
        int meshRenderers = FindObjectsByType<MeshRenderer>(FindObjectsSortMode.None).Length;
        int skinnedMeshRenderers = FindObjectsByType<SkinnedMeshRenderer>(FindObjectsSortMode.None).Length;
        int particleSystems = FindObjectsByType<ParticleSystem>(FindObjectsSortMode.None).Length;

        GUILayout.Label($"MeshRenderer: {meshRenderers} 个");
        GUILayout.Label($"SkinnedMeshRenderer: {skinnedMeshRenderers} 个");
        GUILayout.Label($"ParticleSystem: {particleSystems} 个");
        GUILayout.Label($"总渲染器: {meshRenderers + skinnedMeshRenderers} 个");

        // 统计物理相关组件
        int rigidbodies = FindObjectsByType<Rigidbody>(FindObjectsSortMode.None).Length;
        int colliders = FindObjectsByType<Collider>(FindObjectsSortMode.None).Length;

        GUILayout.Label($"Rigidbody: {rigidbodies} 个");
        GUILayout.Label($"Collider: {colliders} 个");

        // 统计灯光和相机
        int lights = FindObjectsByType<Light>(FindObjectsSortMode.None).Length;
        int cameras = FindObjectsByType<Camera>(FindObjectsSortMode.None).Length;

        GUILayout.Label($"Light: {lights} 个");
        GUILayout.Label($"Camera: {cameras} 个");

        EditorGUILayout.EndVertical();

        // 详细渲染统计
        EditorGUILayout.Space();
        GUILayout.Label("详细渲染统计", EditorStyles.boldLabel);
        EditorGUILayout.BeginVertical(GUI.skin.box);

        var allRenderers = FindObjectsByType<Renderer>(FindObjectsSortMode.None);
        int totalVertices = 0;
        int totalTriangles = 0;

        foreach (var renderer in allRenderers)
        {
            if (renderer is MeshRenderer meshRenderer)
            {
                var filter = meshRenderer.GetComponent<MeshFilter>();
                if (filter != null && filter.sharedMesh != null)
                {
                    totalVertices += filter.sharedMesh.vertexCount;
                    totalTriangles += (int)filter.sharedMesh.GetIndexCount(0) / 3;
                }
            }
            else if (renderer is SkinnedMeshRenderer skinnedMeshRenderer)
            {
                if (skinnedMeshRenderer.sharedMesh != null)
                {
                    totalVertices += skinnedMeshRenderer.sharedMesh.vertexCount;
                    totalTriangles += (int)skinnedMeshRenderer.sharedMesh.GetIndexCount(0) / 3;
                }
            }
        }

        GUILayout.Label($"总顶点数: {totalVertices}");
        GUILayout.Label($"总三角形数: {totalTriangles}");
        GUILayout.Label($"平均每个渲染器顶点: {(float)totalVertices / allRenderers.Length:F0}");
        GUILayout.Label($"平均每个渲染器三角形: {(float)totalTriangles / allRenderers.Length:F0}");

        EditorGUILayout.EndVertical();

        EditorGUILayout.EndScrollView();
    }

    void AnalyzeScene()
    {
        objectCountByType.Clear();
        componentCountByType.Clear();
        totalObjects = 0;
        totalComponents = 0;

        // 使用新的 FindObjectsByType API
        GameObject[] allObjects = FindObjectsByType<GameObject>(FindObjectsSortMode.None);

        foreach (GameObject obj in allObjects)
        {
            if (obj != null)
            {
                totalObjects++;

                // 统计对象类型（通过标签或组件判断）
                string objectType = "GameObject";
                if (obj.CompareTag("Untagged") == false)
                {
                    objectType = $"Tag:{obj.tag}";
                }
                else if (obj.GetComponent<Renderer>() != null)
                {
                    objectType = "Renderable";
                }
                else if (obj.transform.childCount > 0)
                {
                    objectType = "Parent";
                }
                else if (obj.GetComponent<Light>() != null)
                {
                    objectType = "Light";
                }
                else if (obj.GetComponent<Camera>() != null)
                {
                    objectType = "Camera";
                }

                if (objectCountByType.ContainsKey(objectType))
                    objectCountByType[objectType]++;
                else
                    objectCountByType[objectType] = 1;

                // 统计组件
                Component[] components = obj.GetComponents<Component>();
                totalComponents += components.Length;

                foreach (Component component in components)
                {
                    if (component != null)
                    {
                        string componentType = component.GetType().Name;
                        if (componentCountByType.ContainsKey(componentType))
                            componentCountByType[componentType]++;
                        else
                            componentCountByType[componentType] = 1;
                    }
                }
            }
        }

        Debug.Log($"场景分析完成！共分析了 {totalObjects} 个对象和 {totalComponents} 个组件");
    }

    // 兼容性方法：根据 Unity 版本使用正确的 API
    T[] FindAllObjectsOfType<T>() where T : Object
    {
#if UNITY_2023_1_OR_NEWER
        return FindObjectsByType<T>(FindObjectsSortMode.None);
#else
        return FindObjectsOfType<T>();
#endif
    }
}